define([
	'jquery',
	'underscore',
	'backbone',
	'text!templates/HomeView.html',
	'models/Home',
	'models/FolderModel',
	'views/FolderView',
	'views/HomeView'
], function( $, _, Backbone, HomeViewTemplate, HomeModel, FolderModel, FolderView ) {

	var HomeView = Backbone.View.extend({

		tagName:  'div',

		template: _.template( HomeViewTemplate ),

		events: {
		},

		initialize: function() {
			eventHandler.on('HomeView:sortFolders', this.sortFolders, this);
		
			this.getHtml();

			this.initializeFolders();

		},

		initializeFolders: function() {


			this.folderModel = new FolderModel({
				name: this.options.name
			});

			this.folderModel.getAll('initializeFoldersCollection', this)
		},

		initializeFoldersCollection: function( models ) {
			this.folderCollection = new Backbone.Collection();

			for(var x = 0, l = models.length; x < l; x++) {
				models[x] = new Backbone.Model(models[x]);

				(new FolderView({
					model: models[x]
				})).render(this.$el.find('#folders'));

				this.folderCollection.push(models[x]);

				$("#folder_" + models[x].toJSON().id).css("z-index", x);
			}

		},

		sortFolders: function(cid) {
			this.selected = this.folderCollection.get(cid).toJSON();

			for(var x = 0, l = this.folderCollection.length; x < l; x++) {
				var currentFolder = $("#folder_" + this.folderCollection.models[x].id)
				
				if(currentFolder.css("z-index") > $("#folder_" + this.selected['id']).css("z-index")) {
					currentFolder.css("z-index", (currentFolder.css("z-index") - 1));
				}
			}

			$("#folder_" + this.selected['id']).css("z-index", this.folderCollection.length);
		},

		getHtml: function() {
			this.$el.html( this.template() );
		},

		render: function() {
			$(this.options.container).html( this.$el );
		},

		successMethod: function( data ) {
			console.log( data );
		},

		errorMethod: function( data ) {
			console.log( data );
		}
	});

	return HomeView;
});
